package cn.tedu._01vehicle.controller;


import cn.tedu._01vehicle.base.response.JsonResult;
import cn.tedu._01vehicle.base.response.StatusCode;
import cn.tedu._01vehicle.mapper.UserMapper;
import cn.tedu._01vehicle.pojo.dto.UserLoginParam;
import cn.tedu._01vehicle.pojo.dto.UserRegParam;

import cn.tedu._01vehicle.pojo.entity.User;

import cn.tedu._01vehicle.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/v1/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    /**
     * 1. 注册功能的实现
     */
    @PostMapping("reg")
    public JsonResult reg(@RequestBody UserRegParam userRegParam) {
        log.debug("userRegParam = " + userRegParam);

        /**
         1. 接收客户端传递的参数；
         2. 校验数据的合法性；
         3. 校验用户名是否被占用【SELECT接口】；
         SELECT COUNT(*) FROM user WHERE username=?
         3.1 被占用：返回用户名被占用；
         3.2 未被占用：将用户信息插入数据表【INSERT接口】，返回注册成功;
         */
        String username = userRegParam.getUsername();
        int count = userMapper.selectByUsername(username);
        if (count > 0) {      //被占用
            return new JsonResult(StatusCode.USERNAME_EXISTS);
        }

        //未被占用
        User user = new User();
        BeanUtils.copyProperties(userRegParam, user);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        log.debug("user = " + user);

        //调用接口方法
        userMapper.insertUser(user);
        return JsonResult.ok();
    }

    /**
     * 2. 登录功能
      */
   @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginParam userLoginParam){
       log.debug("userLoginParam = " + userLoginParam);
       UserVO userVO = userMapper.selectByUsernameAndPassword(userLoginParam);
       if (userVO == null) {
           return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
       }
       //反馈登陆成功
       return JsonResult.ok(userVO);
   }
}
